import axios from 'axios';
import { ElMessage } from 'element-plus';
import { useAuthStore } from '../stores/auth';
import { useRouter } from 'vue-router';

// 创建 Axios 实例
const instance = axios.create({
  baseURL: '/api', // Vite 代理转发到 http://localhost:8000
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json',
  },
});

// 请求拦截器
instance.interceptors.request.use(
  (config) => {
    const authStore = useAuthStore();
    if (authStore.token) {
      config.headers.Authorization = `Bearer ${authStore.token}`;
    }
    return config;
  },
  (error) => Promise.reject(error)
);

// 响应拦截器
instance.interceptors.response.use(
  (response) => response.data, // 直接返回数据
  (error) => {
    const router = useRouter();
    const authStore = useAuthStore();
    if (error.response?.status === 401) {
      authStore.logout();
      const redirect = encodeURIComponent(window.location.pathname + window.location.search);
      router.push(`/login?redirect=${redirect}`);
      ElMessage.error('请先登录');
      return Promise.reject(new Error('未授权'));
    }
    const message = error.response?.data?.message || '请求失败';
    ElMessage.error(message);
    return Promise.reject(error);
  }
);

export default instance;